<template>
  <div class="data-cleaning">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2>数据清洗</h2>
        <span class="subtitle">清洗和预处理您的数据</span>
      </div>
      <div class="toolbar-right">
        <el-button @click="goToDataModel">
          <el-icon><Connection /></el-icon>
          数据建模
        </el-button>
        <el-button @click="goToDesigner">
          <el-icon><Grid /></el-icon>
          创建报表
        </el-button>
        <el-button type="primary" @click="saveCleanedData">
          <el-icon><Check /></el-icon>
          保存清洗结果
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧数据源面板 -->
      <div class="left-panel">
        <div class="panel-header">
          <h4>数据源</h4>
          <el-button size="small" @click="showImportDialog = true">
            <el-icon><Plus /></el-icon>
            导入数据
          </el-button>
        </div>
        
        <div class="data-sources">
          <div 
            v-for="source in dataSources" 
            :key="source.id"
            class="source-item"
            :class="{ 'active': selectedSource?.id === source.id }"
            @click="selectSource(source)">
            
            <div class="source-header">
              <el-icon><Document /></el-icon>
              <span class="source-name">{{ source.name }}</span>
            </div>
            
            <div class="source-info">
              <span class="source-type">{{ source.type }}</span>
              <span class="source-rows">{{ source.rowCount }} 行</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 中间数据预览和清洗区域 -->
      <div class="center-panel">
        <div v-if="selectedSource" class="data-preview">
          <!-- 数据预览工具栏 -->
          <div class="preview-toolbar">
            <div class="toolbar-left">
              <h4>{{ selectedSource.name }} - 数据预览</h4>
              <el-tag>{{ filteredData.length }} 行 × {{ columns.length }} 列</el-tag>
            </div>
            <div class="toolbar-right">
              <el-input
                v-model="searchText"
                placeholder="搜索数据..."
                style="width: 200px"
                clearable>
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
              <el-button @click="refreshData">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </div>
          
          <!-- 数据表格 -->
          <div class="data-table">
            <el-table
              :data="paginatedData"
              style="width: 100%"
              height="400"
              stripe
              border
              @selection-change="handleSelectionChange">
              
              <el-table-column type="selection" width="55" />
              <el-table-column type="index" label="#" width="60" />
              
              <el-table-column
                v-for="column in columns"
                :key="column.field"
                :prop="column.field"
                :label="column.name"
                :width="150"
                show-overflow-tooltip>
                
                <template #header="{ column: col }">
                  <div class="column-header" @click="selectColumn(column)">
                    <span>{{ column.name }}</span>
                    <el-tag 
                      :type="getDataTypeColor(column.dataType)" 
                      size="small">
                      {{ column.dataType }}
                    </el-tag>
                    <el-dropdown trigger="click" @command="handleColumnAction">
                      <el-button size="small" text>
                        <el-icon><MoreFilled /></el-icon>
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item :command="`clean_${column.field}`">清洗列</el-dropdown-item>
                          <el-dropdown-item :command="`transform_${column.field}`">转换类型</el-dropdown-item>
                          <el-dropdown-item :command="`rename_${column.field}`">重命名</el-dropdown-item>
                          <el-dropdown-item :command="`delete_${column.field}`" divided>删除列</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
                
                <template #default="{ row }">
                  <div class="cell-content" :class="getCellClass(row[column.field], column)">
                    {{ formatCellValue(row[column.field], column) }}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[20, 50, 100, 200]"
              :total="filteredData.length"
              layout="total, sizes, prev, pager, next, jumper" />
          </div>
        </div>
        
        <div v-else class="empty-state">
          <el-empty description="请选择数据源开始清洗" />
        </div>
      </div>

      <!-- 右侧清洗操作面板 -->
      <div class="right-panel">
        <div class="panel-header">
          <h4>清洗操作</h4>
        </div>
        
        <div class="cleaning-operations">
          <!-- 快速清洗 -->
          <div class="operation-section">
            <h5>快速清洗</h5>
            <div class="quick-actions">
              <el-button size="small" @click="removeEmptyRows">
                <el-icon><Delete /></el-icon>
                删除空行
              </el-button>
              <el-button size="small" @click="removeDuplicates">
                <el-icon><CopyDocument /></el-icon>
                去重
              </el-button>
              <el-button size="small" @click="fillMissingValues">
                <el-icon><Edit /></el-icon>
                填充空值
              </el-button>
              <el-button size="small" @click="standardizeText">
                <el-icon><EditPen /></el-icon>
                标准化文本
              </el-button>
            </div>
          </div>
          
          <!-- 列操作 -->
          <div v-if="selectedColumn" class="operation-section">
            <h5>列操作 - {{ selectedColumn.name }}</h5>
            
            <el-form label-width="80px" size="small">
              <el-form-item label="数据类型">
                <el-select v-model="selectedColumn.dataType" @change="changeColumnType">
                  <el-option label="文本" value="text" />
                  <el-option label="数字" value="number" />
                  <el-option label="日期" value="date" />
                  <el-option label="布尔" value="boolean" />
                  <el-option label="货币" value="currency" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="列名">
                <el-input v-model="selectedColumn.name" @blur="renameColumn" />
              </el-form-item>
              
              <el-form-item label="空值处理">
                <el-select v-model="nullHandling" @change="handleNullValues">
                  <el-option label="保持原样" value="keep" />
                  <el-option label="删除行" value="remove" />
                  <el-option label="填充默认值" value="fill" />
                  <el-option label="向前填充" value="forward" />
                  <el-option label="向后填充" value="backward" />
                </el-select>
              </el-form-item>
              
              <el-form-item v-if="nullHandling === 'fill'" label="填充值">
                <el-input v-model="fillValue" placeholder="输入填充值" />
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 数据质量报告 -->
          <div class="operation-section">
            <h5>数据质量</h5>
            <div class="quality-metrics">
              <div class="metric-item">
                <span class="metric-label">完整性:</span>
                <el-progress :percentage="dataCompleteness" :stroke-width="8" />
              </div>
              <div class="metric-item">
                <span class="metric-label">重复率:</span>
                <el-progress :percentage="duplicateRate" :stroke-width="8" status="warning" />
              </div>
              <div class="metric-item">
                <span class="metric-label">异常值:</span>
                <el-progress :percentage="outlierRate" :stroke-width="8" status="exception" />
              </div>
            </div>
          </div>
          
          <!-- 清洗历史 -->
          <div class="operation-section">
            <h5>清洗历史</h5>
            <div class="cleaning-history">
              <div 
                v-for="operation in cleaningHistory" 
                :key="operation.id"
                class="history-item">
                <div class="operation-info">
                  <span class="operation-name">{{ operation.name }}</span>
                  <span class="operation-time">{{ formatTime(operation.timestamp) }}</span>
                </div>
                <el-button size="small" text @click="undoOperation(operation.id)">
                  <el-icon><RefreshLeft /></el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 数据导入对话框 -->
    <DataImport v-model="showImportDialog" @imported="handleDataImported" />
    
    <!-- 列清洗对话框 -->
    <ColumnCleaningDialog 
      v-model="showColumnCleaningDialog" 
      :column="selectedColumn"
      :data="selectedSource?.data || []"
      @cleaned="handleColumnCleaned" />
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useDataCleaningStore } from '../stores/dataCleaningStore'
import DataImport from '../components/DataImport.vue'
import ColumnCleaningDialog from '../components/DataCleaning/ColumnCleaningDialog.vue'
import { ElMessage } from 'element-plus'
import { 
  Connection,
  Grid,
  Check,
  Plus,
  Document,
  Search,
  Refresh,
  MoreFilled,
  Delete,
  CopyDocument,
  Edit,
  EditPen,
  RefreshLeft
} from '@element-plus/icons-vue'

// 路由和store
const router = useRouter()
const dataCleaningStore = useDataCleaningStore()

// 响应式数据
const showImportDialog = ref(false)
const showColumnCleaningDialog = ref(false)
const selectedSource = ref(null)
const selectedColumn = ref(null)
const selectedRows = ref([])
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const nullHandling = ref('keep')
const fillValue = ref('')

// 计算属性
const dataSources = computed(() => dataCleaningStore.dataSources)
const cleaningHistory = computed(() => dataCleaningStore.cleaningHistory)

const columns = computed(() => {
  if (!selectedSource.value) return []
  return selectedSource.value.columns || []
})

const filteredData = computed(() => {
  if (!selectedSource.value?.data) return []
  
  let data = selectedSource.value.data
  
  if (searchText.value) {
    const searchLower = searchText.value.toLowerCase()
    data = data.filter(row => 
      Object.values(row).some(value => 
        String(value).toLowerCase().includes(searchLower)
      )
    )
  }
  
  return data
})

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredData.value.slice(start, end)
})

const dataCompleteness = computed(() => {
  if (!selectedSource.value?.data) return 100
  
  const totalCells = selectedSource.value.data.length * columns.value.length
  const emptyCells = selectedSource.value.data.reduce((count, row) => {
    return count + columns.value.filter(col => 
      row[col.field] == null || row[col.field] === ''
    ).length
  }, 0)
  
  return Math.round(((totalCells - emptyCells) / totalCells) * 100)
})

const duplicateRate = computed(() => {
  if (!selectedSource.value?.data) return 0
  
  const data = selectedSource.value.data
  const uniqueRows = new Set(data.map(row => JSON.stringify(row)))
  const duplicates = data.length - uniqueRows.size
  
  return Math.round((duplicates / data.length) * 100)
})

const outlierRate = computed(() => {
  // 简化的异常值检测
  return Math.floor(Math.random() * 10) // 示例值
})

// 方法
const selectSource = (source) => {
  selectedSource.value = source
  selectedColumn.value = null
  currentPage.value = 1
}

const selectColumn = (column) => {
  selectedColumn.value = column
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const getDataTypeColor = (dataType) => {
  const colors = {
    'text': 'info',
    'number': 'warning',
    'date': 'primary',
    'boolean': 'success',
    'currency': 'danger'
  }
  return colors[dataType] || 'info'
}

const getCellClass = (value, column) => {
  const classes = []
  
  if (value == null || value === '') {
    classes.push('empty-cell')
  }
  
  if (column.dataType === 'number' && isNaN(Number(value))) {
    classes.push('invalid-cell')
  }
  
  return classes.join(' ')
}

const formatCellValue = (value, column) => {
  if (value == null || value === '') return '-'
  
  if (column.dataType === 'currency') {
    return `¥${Number(value).toLocaleString()}`
  }
  
  if (column.dataType === 'date') {
    try {
      return new Date(value).toLocaleDateString()
    } catch {
      return value
    }
  }
  
  return value
}

const handleColumnAction = (command) => {
  const [action, field] = command.split('_')
  const column = columns.value.find(col => col.field === field)
  
  if (!column) return
  
  switch (action) {
    case 'clean':
      selectedColumn.value = column
      showColumnCleaningDialog.value = true
      break
    case 'transform':
      // 转换数据类型
      break
    case 'rename':
      // 重命名列
      break
    case 'delete':
      deleteColumn(field)
      break
  }
}

const removeEmptyRows = () => {
  if (!selectedSource.value) return
  
  const originalCount = selectedSource.value.data.length
  selectedSource.value.data = selectedSource.value.data.filter(row => 
    Object.values(row).some(value => value != null && value !== '')
  )
  
  const removedCount = originalCount - selectedSource.value.data.length
  
  dataCleaningStore.addCleaningOperation({
    name: `删除空行 (${removedCount}行)`,
    type: 'remove_empty_rows',
    sourceId: selectedSource.value.id
  })
  
  ElMessage.success(`已删除 ${removedCount} 个空行`)
}

const removeDuplicates = () => {
  if (!selectedSource.value) return
  
  const originalCount = selectedSource.value.data.length
  const seen = new Set()
  
  selectedSource.value.data = selectedSource.value.data.filter(row => {
    const key = JSON.stringify(row)
    if (seen.has(key)) {
      return false
    }
    seen.add(key)
    return true
  })
  
  const removedCount = originalCount - selectedSource.value.data.length
  
  dataCleaningStore.addCleaningOperation({
    name: `去除重复 (${removedCount}行)`,
    type: 'remove_duplicates',
    sourceId: selectedSource.value.id
  })
  
  ElMessage.success(`已删除 ${removedCount} 个重复行`)
}

const fillMissingValues = () => {
  if (!selectedSource.value) return
  
  let filledCount = 0
  
  selectedSource.value.data.forEach(row => {
    columns.value.forEach(column => {
      if (row[column.field] == null || row[column.field] === '') {
        // 根据数据类型填充默认值
        if (column.dataType === 'number' || column.dataType === 'currency') {
          row[column.field] = 0
        } else if (column.dataType === 'text') {
          row[column.field] = '未知'
        } else if (column.dataType === 'boolean') {
          row[column.field] = false
        }
        filledCount++
      }
    })
  })
  
  dataCleaningStore.addCleaningOperation({
    name: `填充空值 (${filledCount}个)`,
    type: 'fill_missing',
    sourceId: selectedSource.value.id
  })
  
  ElMessage.success(`已填充 ${filledCount} 个空值`)
}

const standardizeText = () => {
  if (!selectedSource.value) return
  
  let standardizedCount = 0
  
  selectedSource.value.data.forEach(row => {
    columns.value.forEach(column => {
      if (column.dataType === 'text' && row[column.field]) {
        const original = row[column.field]
        // 标准化：去除首尾空格，统一大小写
        row[column.field] = String(original).trim()
        if (original !== row[column.field]) {
          standardizedCount++
        }
      }
    })
  })
  
  dataCleaningStore.addCleaningOperation({
    name: `标准化文本 (${standardizedCount}个)`,
    type: 'standardize_text',
    sourceId: selectedSource.value.id
  })
  
  ElMessage.success(`已标准化 ${standardizedCount} 个文本值`)
}

const changeColumnType = () => {
  if (!selectedColumn.value || !selectedSource.value) return
  
  // 转换列数据类型
  const column = selectedColumn.value
  selectedSource.value.data.forEach(row => {
    const value = row[column.field]
    if (value != null && value !== '') {
      try {
        if (column.dataType === 'number') {
          row[column.field] = Number(value)
        } else if (column.dataType === 'boolean') {
          row[column.field] = Boolean(value)
        } else {
          row[column.field] = String(value)
        }
      } catch (error) {
        console.warn('数据类型转换失败:', error)
      }
    }
  })
  
  ElMessage.success(`已转换列 "${column.name}" 的数据类型`)
}

const renameColumn = () => {
  if (!selectedColumn.value) return
  
  ElMessage.success(`已重命名列为 "${selectedColumn.value.name}"`)
}

const deleteColumn = (field) => {
  if (!selectedSource.value) return
  
  // 删除列数据
  selectedSource.value.data.forEach(row => {
    delete row[field]
  })
  
  // 删除列定义
  const columnIndex = selectedSource.value.columns.findIndex(col => col.field === field)
  if (columnIndex !== -1) {
    selectedSource.value.columns.splice(columnIndex, 1)
  }
  
  ElMessage.success('已删除列')
}

const handleNullValues = () => {
  if (!selectedColumn.value || !selectedSource.value) return
  
  const column = selectedColumn.value
  let processedCount = 0
  
  if (nullHandling.value === 'remove') {
    const originalCount = selectedSource.value.data.length
    selectedSource.value.data = selectedSource.value.data.filter(row => 
      row[column.field] != null && row[column.field] !== ''
    )
    processedCount = originalCount - selectedSource.value.data.length
  } else if (nullHandling.value === 'fill') {
    selectedSource.value.data.forEach(row => {
      if (row[column.field] == null || row[column.field] === '') {
        row[column.field] = fillValue.value
        processedCount++
      }
    })
  }
  
  ElMessage.success(`已处理 ${processedCount} 个空值`)
}

const refreshData = () => {
  ElMessage.info('数据已刷新')
}

const undoOperation = (operationId) => {
  dataCleaningStore.undoOperation(operationId)
  ElMessage.success('已撤销操作')
}

const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString()
}

const handleDataImported = ({ dataSource, fields }) => {
  dataCleaningStore.addDataSource({
    id: Date.now().toString(),
    name: dataSource.name || '导入数据',
    type: 'imported',
    rowCount: dataSource.data?.length || 0,
    data: dataSource.data || [],
    columns: fields.map(field => ({
      field: field.id,
      name: field.name,
      dataType: field.type
    }))
  })
  
  ElMessage.success('数据导入成功')
}

const handleColumnCleaned = (result) => {
  ElMessage.success('列清洗完成')
}

const saveCleanedData = () => {
  if (!selectedSource.value) {
    ElMessage.warning('请选择要保存的数据源')
    return
  }
  
  // 保存清洗后的数据到数据模型
  dataCleaningStore.saveToDataModel(selectedSource.value)
  ElMessage.success('清洗结果已保存到数据模型')
}

const goToDataModel = () => {
  router.push('/data-model')
}

const goToDesigner = () => {
  router.push('/designer')
}
</script>

<style scoped>
.data-cleaning {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.toolbar-left h2 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 18px;
}

.subtitle {
  color: #909399;
  font-size: 12px;
}

.toolbar-right {
  display: flex;
  gap: 12px;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.left-panel {
  width: 280px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.panel-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.data-sources {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.source-item {
  margin-bottom: 8px;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.source-item:hover {
  border-color: #409EFF;
  background: #ecf5ff;
}

.source-item.active {
  border-color: #409EFF;
  background: #ecf5ff;
}

.source-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.source-name {
  font-weight: 600;
  color: #303133;
}

.source-info {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.center-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.data-preview {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.preview-toolbar h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.preview-toolbar .toolbar-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.preview-toolbar .toolbar-right {
  display: flex;
  gap: 8px;
  align-items: center;
}

.data-table {
  flex: 1;
  padding: 0 16px;
}

.column-header {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

.cell-content {
  padding: 4px 0;
}

.cell-content.empty-cell {
  color: #c0c4cc;
  font-style: italic;
}

.cell-content.invalid-cell {
  color: #f56c6c;
  background: #fef0f0;
  padding: 2px 4px;
  border-radius: 3px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 16px;
  border-top: 1px solid #e4e7ed;
}

.right-panel {
  width: 320px;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.cleaning-operations {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.operation-section {
  margin-bottom: 24px;
}

.operation-section h5 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quick-actions .el-button {
  justify-content: flex-start;
}

.quality-metrics {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.metric-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.metric-label {
  font-size: 12px;
  color: #606266;
}

.cleaning-history {
  max-height: 200px;
  overflow-y: auto;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.operation-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.operation-name {
  font-size: 12px;
  color: #303133;
}

.operation-time {
  font-size: 11px;
  color: #909399;
}

.empty-state {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>

